package com.market.member.service.login;

import cn.hutool.core.util.ObjectUtil;
import com.block.common.bean.CommonParam;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.model.dto.LoginReqDTO;
import com.block.common.model.dto.NewMemberDTO;
import com.block.common.service.IMemberCommonService;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.MemberBaseInfo;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.market.member.enums.UserRegTypeEnum;
import com.market.member.enums.UserTypeEnum;
import com.market.member.model.dto.LoginResultDTO;
import com.market.member.service.ILoginTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class RandomLoginServiceImpl extends ILoginTypeService {

    @Resource
    MemberBaseInfoMapper memberBaseInfoMapper;
    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ResponseVo toLogin(LoginReqDTO loginReqDTO) {

        String mobile = loginReqDTO.getMobile();

        MemberBaseInfo memberInfo = memberBaseInfoMapper.getBaseUserInfoByPhoneLock(mobile);
        boolean isNewMember = false;
        if (memberInfo == null){

            NewMemberDTO newMemberDTO = new NewMemberDTO();
            newMemberDTO.setMobile(loginReqDTO.getMobile());
            newMemberDTO.setChannelCode(loginReqDTO.getChannelCode());
            newMemberDTO.setChannelName(loginReqDTO.getChannelName());
            newMemberDTO.setRegAppCode(loginReqDTO.getAppCode());
            newMemberDTO.setRegReqIP(loginReqDTO.getReqIp());
            newMemberDTO.setType(UserTypeEnum.RANDOM.getValue());
            newMemberDTO.setRegType(UserRegTypeEnum.NORMAL.getValue());

            memberInfo = memberCommonService.saveNewMemberInfo(newMemberDTO);
            if (ObjectUtil.isEmpty(memberInfo)){
                log.error("【随机手机号直接登陆】创建用户失败");
                return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "登录失败，请重试");
            }
            isNewMember = true;
        }

        //
        LoginResultDTO loginResultDTO = new LoginResultDTO();
        loginResultDTO.setUid(memberInfo.getUid());
        loginResultDTO.setNewMember(isNewMember);
        loginResultDTO.setMemberBaseInfo(memberInfo);


        return new ResponseVo(AppRspCodeConstant.SUCCESS, loginResultDTO);
    }
}
